﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.WebApp.ViewModel;
using System.Web.Security;
using XSTDZ.ERP.Infrastructure;

namespace XSTDZ.ERP.WebApp.Controllers
{
    [NoAuthorizated]
    public class AccountController : Controller
    {
        private readonly IUserService userServiceImpl = ServiceLocator.Instance.GetService<IUserService>();
        #region 登陆
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(UserLoginViewModel user)
        {

            #region 验证数据
            if (user.UserName == null || user.UserPassword == null || user.ValidateCode == null)
            {
                return View();
            }
            #endregion

            if (ModelState.IsValid)
            {
                var userModel = new UserModel();
                //验证码
                if (Session["ValidateCode"] == null)
                {
                    ModelState.AddModelError("ValidateCode", "验证码异常！");
                    return View();
                }
                if (Session["ValidateCode"].ToString() != user.ValidateCode.Trim())
                {
                    ModelState.AddModelError("ValidateCode", "验证码错误！");
                    return View();
                }

                if (user.UserName == "admin" && user.UserPassword == "admin")
                {
                    userModel.InitAdmin();
                    var userID = CryptographerLite.Encrypt(XSTDZ.ERP.Infrastructure.SystemConfig.AdminId);
                    FormsAuthentication.SetAuthCookie(userID, false);
                    Response.Redirect("~/Home/Index");
                }
                else
                {

                    var userdto = userServiceImpl.GetUser(user.UserName, CryptographerLite.Encrypt(user.UserPassword));
                    if (userdto != null)
                    {
                        if (userdto.AccountName == user.UserName)
                        {
                           var url= userModel.Login(this.HttpContext, userdto.AccountName, userdto.Id.ToString());
                           Response.Redirect(url);
                        }
                    }
                }
            }
            return View();
        }
        #endregion
        /// <summary>
        /// 登陆退出
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Redirect(FormsAuthentication.LoginUrl);
            return Content("9");
        }
    }
}
